package cn.simon.service.Impl;

import cn.simon.exception.GlobalException;
import cn.simon.mapper.OrderMapper;
import cn.simon.mapper.SeckillGoodsMapper;
import cn.simon.mapper.SeckillOrderMapper;
import cn.simon.pojo.*;
import cn.simon.service.IGoodsService;
import cn.simon.service.ISeckillOrderService;
import cn.simon.vo.GoodsVo;
import cn.simon.vo.OrderVo;
import cn.simon.vo.RespBeanEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 秒杀订单表 服务实现类
 * </p>
 * simon-yian 开心
 * @author simon-yian

 */
@Log
@Service
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements ISeckillOrderService {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SeckillOrderMapper seckillOrderMapper;
    @Autowired
    private IGoodsService iGoodsService;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public OrderVo findOrderVoByorderId(Long orderId) {

        OrderVo orderVo = new OrderVo();

        Order order = orderMapper.selectById(orderId);
        if(order == null){
            throw new GlobalException(RespBeanEnum.ORDER_NOEXIST);
        }
        GoodsVo goodsVo = (GoodsVo) iGoodsService.findGoodsVoById(order.getGoodsId());
        orderVo.setOrder(order);
        orderVo.setGoods(goodsVo);
        return orderVo;

    }
    /**
     * @功能描述: 获取秒杀结果
     * @Param:
     * @Return: orderId , -1 秒杀失败， 0 秒杀排队中， >0 秒杀成功返回订单号
     * @Author simon-yi'an
     * @Date 2022/11/7 14:04
     */
    @Override
    public Long getResult(User user, Long goodsId) {
       SeckillOrder seckillOrder = seckillOrderMapper.selectOne(new QueryWrapper<SeckillOrder>()
               .eq("user_id",user.getId())
               .eq("goods_id",goodsId));
       if(seckillOrder != null){
           return seckillOrder.getOrderId();
           //判断redis中该商品是否还有记录，如果有记录说明库存已经完了，若没有表明还有库存
       }else if (redisTemplate.hasKey("isStockEmpty:"+goodsId)) {
           return -1l;
       }else{
           return 0l;
       }
    }
}
